<template>
  <div class="orders-container">
    <el-card class="header-card">
      <h2><el-icon><List /></el-icon> 历史订单</h2>
    </el-card>

    <el-card v-loading="loading">
      <el-empty v-if="orders.length === 0 && !loading" description="暂无订单记录" />

      <transition-group name="order-fade" tag="div" class="orders-list">
        <div class="order-item" v-for="order in orders" :key="order.orderId" @click="showOrderDetail(order)" :class="{ 'clickable': true }">
          <div class="order-header">
            <div class="order-info">
              <span class="order-no">订单号：{{ order.orderNo }}</span>
              <el-tag :type="getOrderStatusType(order.orderStatus)" class="order-status-tag">
                {{ getOrderStatusText(order.orderStatus) }}
              </el-tag>
            </div>
            <div class="order-actions">
              <el-button
                type="primary"
                size="small"
                :icon="Comment"
                v-if="!hasComment(order.orderId!)"
                @click.stop="showCommentDialog(order)"
              >
                订单评论
              </el-button>
              <el-button
                type="success"
                size="small"
                :icon="Comment"
                v-else
                disabled
              >
                已评论
              </el-button>
              <el-button
                type="danger"
                size="small"
                :icon="Delete"
                @click.stop="handleDeleteOrder(order.orderId!)"
              >
                删除
              </el-button>
            </div>
          </div>

          <div class="order-body">
            <div class="delivery-info">
              <p><strong>联系人：</strong>{{ order.contactName }}</p>
              <p><strong>联系电话：</strong>{{ order.contactPhone }}</p>
              <p><strong>配送地址：</strong>{{ order.deliveryAddress }}</p>
              <p v-if="order.remark"><strong>备注：</strong>{{ order.remark }}</p>
            </div>
            <div class="order-meta">
              <p><strong>下单时间：</strong>{{ formatTime(order.createTime) }}</p>
              <p><strong>订单总额：</strong><span class="total-amount">¥{{ order.totalAmount }}</span></p>
            </div>
          </div>
        </div>
      </transition-group>
    </el-card>

    <!-- 订单评论对话框 -->
    <el-dialog
      v-model="showCommentForm"
      title="订单评论"
      width="600px"
      @close="resetCommentForm"
    >
      <el-form :model="commentForm" :rules="commentRules" ref="commentFormRef" label-width="80px">
        <el-form-item label="评分" prop="rating">
          <el-rate v-model="commentForm.rating" :max="5" />
        </el-form-item>
        <el-form-item label="评论内容" prop="commentContent">
          <el-input
            v-model="commentForm.commentContent"
            type="textarea"
            :rows="4"
            placeholder="请输入评论内容"
          />
        </el-form-item>
        <el-form-item label="评论照片" prop="commentImages">
          <el-upload
            ref="uploadRef"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
            :file-list="commentForm.fileList"
            list-type="picture-card"
            :limit="3"
            :on-exceed="handleExceed"
            accept="image/*"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">支持上传3张照片，每张不超过2MB</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCommentForm = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitComment" :loading="submitting">提交评论</el-button>
      </template>
    </el-dialog>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="showOrderDetailDialog"
      :title="`订单详情 - ${selectedOrder?.orderNo || ''}`"
      width="900px"
      @close="resetOrderDetail"
      class="order-detail-dialog"
      :close-on-click-modal="false"
    >
      <div v-if="selectedOrder" class="order-detail-content">
        <!-- 订单基本信息 -->
        <el-card class="order-info-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span>订单信息</span>
              <el-tag :type="getOrderStatusType(selectedOrder.orderStatus)">
                {{ getOrderStatusText(selectedOrder.orderStatus) }}
              </el-tag>
            </div>
          </template>
          <div class="order-basic-info">
            <div class="info-row">
              <span class="label">订单号：</span>
              <span class="value">{{ selectedOrder.orderNo }}</span>
            </div>
            <div class="info-row">
              <span class="label">下单时间：</span>
              <span class="value">{{ formatTime(selectedOrder.createTime) }}</span>
            </div>
            <div class="info-row">
              <span class="label">联系人：</span>
              <span class="value">{{ selectedOrder.contactName }}</span>
            </div>
            <div class="info-row">
              <span class="label">联系电话：</span>
              <span class="value">{{ selectedOrder.contactPhone }}</span>
            </div>
            <div class="info-row">
              <span class="label">配送地址：</span>
              <span class="value">{{ selectedOrder.deliveryAddress }}</span>
            </div>
            <div class="info-row" v-if="selectedOrder.remark">
              <span class="label">备注：</span>
              <span class="value">{{ selectedOrder.remark }}</span>
            </div>
          </div>
        </el-card>

        <!-- 订单商品详情 -->
        <el-card class="order-items-card" shadow="never">
          <template #header>
            <span>商品详情</span>
          </template>
          <div v-loading="orderDetailsLoading">
            <el-empty v-if="orderDetails.length === 0 && !orderDetailsLoading" description="暂无商品信息" />
            <div v-else class="order-items-list">
              <div class="order-item-detail" v-for="item in orderDetails" :key="item.detailId">
                <div class="item-image">
                  <img 
                    :src="getDishImageUrl(item.dishId)" 
                    :alt="item.dishName"
                    @error="handleImageError"
                    class="dish-image"
                  />
                </div>
                <div class="item-content">
                  <div class="item-info">
                    <div class="item-name">{{ item.dishName }}</div>
                    <div class="item-price">¥{{ item.dishPrice }}</div>
                  </div>
                  <div class="item-quantity-info">
                    <div class="item-quantity">×{{ item.quantity }}</div>
                    <div class="item-subtotal">¥{{ item.subtotal }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 订单总计 -->
        <el-card class="order-total-card" shadow="never">
          <div class="total-info">
            <span class="total-label">订单总额：</span>
            <span class="total-amount">¥{{ selectedOrder.totalAmount }}</span>
          </div>
        </el-card>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { List, Delete, Comment, Plus } from '@element-plus/icons-vue';
import { getOrdersByUserId, deleteOrder, getOrderDetailsByOrderId } from '@/api/order';
import { createComment, getCommentsByUserId } from '@/api/comment';
import { getDishById } from '@/api/dish';
import { useUserStore } from '@/stores/user';
import type { Order, Comment as CommentType, Dish, OrderDetail } from '@/types';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';

const userStore = useUserStore();

const orders = ref<Order[]>([]);
const comments = ref<CommentType[]>([]);
const loading = ref(false);
const showCommentForm = ref(false);
const submitting = ref(false);
const commentFormRef = ref<FormInstance>();
const uploadRef = ref();
const currentOrder = ref<Order | null>(null);

// 照片上传相关
const uploadUrl = 'http://localhost:8060/api/files/upload';
const uploadHeaders = {
  'Authorization': 'Bearer ' + localStorage.getItem('token') || ''
};

// 订单详情相关变量
const showOrderDetailDialog = ref(false);
const selectedOrder = ref<Order | null>(null);
const orderDetails = ref<OrderDetail[]>([]);
const orderDetailsLoading = ref(false);
const dishCache = ref<Map<number, Dish>>(new Map());

const commentForm = reactive({
  rating: 5,
  commentContent: '',
  commentImages: '',
  fileList: [] as any[]
});

const commentRules: FormRules = {
  rating: [
    { required: true, message: '请选择评分', trigger: 'change' }
  ],
  commentContent: [
    { required: true, message: '请输入评价内容', trigger: 'blur' }
  ]
};

// 加载订单列表（只显示已支付的订单）
const loadOrders = async () => {
  if (!userStore.userId) return;
  
  loading.value = true;
  try {
    const response = await getOrdersByUserId(userStore.userId);
    if (response.operateResult === 'SUCC' && response.data) {
      // 只显示已支付（orderStatus === '1'）和已完成（orderStatus === '2'）的订单
      orders.value = response.data
        .filter(order => order.orderStatus === '1' || order.orderStatus === '2')
        .sort((a, b) => {
          return new Date(b.createTime || '').getTime() - new Date(a.createTime || '').getTime();
        });
    } else {
      orders.value = [];
    }
  } catch (error) {
    ElMessage.error('加载订单失败');
    orders.value = [];
  } finally {
    loading.value = false;
  }
};

// 加载用户评论
const loadComments = async () => {
  if (!userStore.userId) return;
  
  try {
    const response = await getCommentsByUserId(userStore.userId);
    if (response.operateResult === 'SUCC' && response.data) {
      comments.value = response.data;
    }
  } catch (error) {
  }
};

// 检查订单是否已评价
const hasComment = (orderId: number) => {
  return comments.value.some(c => c.orderId === orderId);
};

// 获取订单状态类型
const getOrderStatusType = (status?: string) => {
  const statusMap: Record<string, string> = {
    '0': 'warning',
    '1': 'info',
    '2': 'success',
    '3': 'danger'
  };
  return statusMap[status || '0'];
};

// 获取订单状态文本
const getOrderStatusText = (status?: string) => {
  const statusMap: Record<string, string> = {
    '0': '待支付',
    '1': '已支付',
    '2': '已完成',
    '3': '已取消'
  };
  return statusMap[status || '0'];
};

// 格式化时间 - 显示完整日期时间
const formatTime = (time?: string) => {
  if (!time) return '';
  const date = new Date(time);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  });
};

// 显示评价对话框
const showCommentDialog = (order: Order) => {
  currentOrder.value = order;
  showCommentForm.value = true;
};

// 提交评价
const handleSubmitComment = async () => {
  if (!commentFormRef.value || !currentOrder.value) return;
  
  await commentFormRef.value.validate(async (valid) => {
    if (!valid) return;
    
    if (!userStore.userId) {
      ElMessage.warning('请先登录');
      return;
    }

    submitting.value = true;
    try {
      // 这里假设订单只包含一个菜品，实际应该关联订单详情
      // 由于后端限制，我们使用订单ID作为dishId的占位符
      const response = await createComment({
        orderId: currentOrder.value.orderId!,
        userId: userStore.userId!,
        dishId: currentOrder.value.orderId!, // 临时使用订单ID，实际应该从订单详情获取
        rating: commentForm.rating,
        commentContent: commentForm.commentContent,
        commentImages: commentForm.commentImages,
        commentStatus: '0'
      });

      if (response.operateResult === 'SUCC') {
        ElMessage.success('评价成功！');
        showCommentForm.value = false;
        await loadComments();
      } else {
        ElMessage.error(response.errorMsg || '评价失败');
      }
    } catch (error: any) {
      ElMessage.error(error.message || '评价失败');
    } finally {
      submitting.value = false;
    }
  });
};

// 删除订单
const handleDeleteOrder = (orderId: number) => {
  ElMessageBox.confirm('确定要删除该订单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await deleteOrder(orderId);
      if (response.operateResult === 'SUCC') {
        ElMessage.success('删除成功');
        await loadOrders();
      } else {
        ElMessage.error(response.errorMsg || '删除失败');
      }
    } catch (error: any) {
      ElMessage.error(error.message || '删除失败');
    }
  }).catch(() => {});
};

// 照片上传处理
const handleUploadSuccess = (response: any, file: any) => {
  if (response.operateResult === 'SUCC') {
    const imageUrl = response.data;
    if (commentForm.commentImages) {
      commentForm.commentImages += ',' + imageUrl;
    } else {
      commentForm.commentImages = imageUrl;
    }
    ElMessage.success('照片上传成功');
  } else {
    ElMessage.error('照片上传失败：' + response.errorMsg);
  }
};

const handleUploadError = (error: any) => {
  ElMessage.error('照片上传失败：' + error.message);
};

const beforeUpload = (file: any) => {
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!');
    return false;
  }
  return true;
};

const handleExceed = () => {
  ElMessage.warning('最多只能上传3张照片');
};

// 重置评价表单
const resetCommentForm = () => {
  commentFormRef.value?.resetFields();
  commentForm.commentImages = '';
  commentForm.fileList = [];
  uploadRef.value?.clearFiles();
  currentOrder.value = null;
};

// 显示订单详情
const showOrderDetail = async (order: Order) => {
  selectedOrder.value = order;
  showOrderDetailDialog.value = true;
  
  // 加载订单详情
  orderDetailsLoading.value = true;
  try {
    const response = await getOrderDetailsByOrderId(order.orderId!);
    if (response.operateResult === 'SUCC' && response.data) {
      orderDetails.value = response.data;
      
      // 加载商品信息到缓存
      await loadDishInfoForOrderDetails(response.data);
    } else {
      orderDetails.value = [];
      ElMessage.warning('获取订单详情失败');
    }
  } catch (error: any) {
    orderDetails.value = [];
    ElMessage.error('获取订单详情失败: ' + error.message);
  } finally {
    orderDetailsLoading.value = false;
  }
};

// 为订单详情加载商品信息
const loadDishInfoForOrderDetails = async (orderDetails: OrderDetail[]) => {
  const dishIds = [...new Set(orderDetails.map(item => item.dishId))];
  
  for (const dishId of dishIds) {
    // 如果缓存中没有该商品信息，则加载
    if (!dishCache.value.has(dishId)) {
      try {
        const response = await getDishById(dishId);
        if (response.operateResult === 'SUCC' && response.data) {
          dishCache.value.set(dishId, response.data);
        }
      } catch (error) {
        console.warn(`Failed to load dish info for dishId: ${dishId}`, error);
      }
    }
  }
};

// 重置订单详情
const resetOrderDetail = () => {
  selectedOrder.value = null;
  orderDetails.value = [];
};

// 获取商品图片URL
const getDishImageUrl = (dishId: number) => {
  // 从缓存中获取商品信息
  const dish = dishCache.value.get(dishId);
  if (dish && dish.dishImage) {
    // 如果商品有图片信息，使用它
    if (dish.dishImage.startsWith('http')) {
      return dish.dishImage;
    }
    return `http://localhost:8060${dish.dishImage}`;
  }
  
  // 如果没有图片信息，返回默认图片
  return 'https://via.placeholder.com/80x80?text=No+Image';
};

// 图片加载错误处理
const handleImageError = (e: Event) => {
  const target = e.target as HTMLImageElement;
  target.src = 'https://via.placeholder.com/80x80?text=No+Image';
};

onMounted(() => {
  loadOrders();
  loadComments();
});
</script>

<style scoped>
.orders-container {
  animation: fadeIn 0.5s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.header-card {
  margin-bottom: 20px;
}

.header-card h2 {
  margin: 0;
  display: flex;
  align-items: center;
  gap: 10px;
  color: #303133;
}

.orders-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.order-item {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.order-item.clickable {
  cursor: pointer;
}

.order-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.order-item.clickable:hover {
  border-color: #409eff;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
}

.order-fade-enter-active,
.order-fade-leave-active {
  transition: all 0.3s ease;
}

.order-fade-enter-from {
  opacity: 0;
  transform: translateX(-20px);
}

.order-fade-leave-to {
  opacity: 0;
  transform: translateX(20px);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
}

.order-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.order-no {
  font-weight: bold;
  color: #303133;
}

.order-actions {
  display: flex;
  gap: 10px;
}

.order-body {
  padding: 20px;
  display: flex;
  justify-content: space-between;
}

.delivery-info {
  flex: 1;
}

.delivery-info p,
.order-meta p {
  margin: 8px 0;
  color: #606266;
}

.order-meta {
  text-align: right;
  min-width: 250px;
}

.total-amount {
  font-size: 20px;
  font-weight: bold;
  color: #f56c6c;
}

/* 订单详情对话框样式 */
.order-detail-content {
  max-height: 600px;
  overflow-y: auto;
  padding: 4px;
}

.order-info-card,
.order-items-card,
.order-total-card {
  margin-bottom: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid #f0f0f0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  color: #2c3e50;
}

.order-basic-info {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.info-row {
  display: flex;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f5f5f5;
}

.info-row:last-child {
  border-bottom: none;
}

.info-row .label {
  font-weight: 600;
  color: #606266;
  min-width: 90px;
  font-size: 14px;
}

.info-row .value {
  color: #303133;
  font-size: 14px;
}

.order-items-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.order-item-detail {
  display: flex;
  align-items: center;
  padding: 16px;
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  border-radius: 12px;
  border: 1px solid #e9ecef;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.04);
}

.order-item-detail:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  border-color: #409eff;
}

.item-image {
  margin-right: 16px;
  flex-shrink: 0;
}

.dish-image {
  width: 80px;
  height: 80px;
  border-radius: 12px;
  object-fit: cover;
  border: 2px solid #f0f0f0;
  transition: all 0.3s ease;
}

.dish-image:hover {
  transform: scale(1.05);
  border-color: #409eff;
}

.item-content {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.item-info {
  flex: 1;
}

.item-name {
  font-weight: 600;
  color: #2c3e50;
  font-size: 16px;
  margin-bottom: 4px;
}

.item-price {
  color: #909399;
  font-size: 14px;
}

.item-quantity-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.item-quantity {
  color: #606266;
  font-weight: 600;
  font-size: 16px;
  background: #f0f0f0;
  padding: 4px 12px;
  border-radius: 20px;
}

.item-subtotal {
  font-weight: 700;
  color: #f56c6c;
  font-size: 18px;
  min-width: 80px;
  text-align: right;
}

.total-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  color: white;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.total-label {
  font-size: 18px;
  font-weight: 600;
}

.total-amount {
  font-size: 28px;
  font-weight: bold;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

/* 订单详情对话框全局样式 */
:deep(.order-detail-dialog) {
  border-radius: 16px;
  overflow: hidden;
}

:deep(.order-detail-dialog .el-dialog__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px 24px;
  border-radius: 16px 16px 0 0;
}

:deep(.order-detail-dialog .el-dialog__title) {
  color: white;
  font-weight: 600;
  font-size: 18px;
}

:deep(.order-detail-dialog .el-dialog__headerbtn .el-dialog__close) {
  color: white;
  font-size: 20px;
}

:deep(.order-detail-dialog .el-dialog__headerbtn .el-dialog__close:hover) {
  color: #f0f0f0;
}

:deep(.order-detail-dialog .el-dialog__body) {
  padding: 24px;
  background: #f8f9fa;
}

:deep(.order-detail-dialog .el-dialog__footer) {
  background: #f8f9fa;
  padding: 16px 24px;
  border-radius: 0 0 16px 16px;
}

/* 订单状态标签样式 */
.order-status-tag {
  font-weight: 600;
  border-radius: 20px;
  padding: 4px 12px;
  font-size: 12px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

:deep(.order-status-tag.el-tag--success) {
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
  border: none;
  color: white;
}

:deep(.order-status-tag.el-tag--warning) {
  background: linear-gradient(135deg, #e6a23c 0%, #f0c78a 100%);
  border: none;
  color: white;
}

:deep(.order-status-tag.el-tag--info) {
  background: linear-gradient(135deg, #909399 0%, #b1b3b8 100%);
  border: none;
  color: white;
}

/* 上传组件样式 */
.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
  text-align: center;
}

:deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
}

:deep(.el-upload--picture-card:hover) {
  border-color: #409eff;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 100px;
  height: 100px;
  border-radius: 6px;
}
</style>
